<!-- 类目管理 -->
<template>
    <div>
        <el-card class="box-card">
            <div class="custom-tree-container">
                <el-tree :data="[{title:'全部类目',id:0,childrenList:treedata}]" :props="{ label: 'title', children: 'childrenList' }" node-key="id"
                    default-expand-all :expand-on-click-node="false" element-londing-text="正在加载中..."
                    v-loading="listLoading">
                    <template #default="{ node, data }">
                        <span class="custom-tree-node">
                            <span>
                                <span>
                                    <img :src="data.picUrl" class="tree_icon" />
                                </span>
                                {{ node.label }}
                                <span>
                                    <el-tag type="danger" v-show="data.level == 0">一级</el-tag>
                                    <el-tag type="warning" v-show="data.level == 1">二级</el-tag>
                                    <el-tag type="success" v-show="data.level == 2">三级</el-tag>
                                </span>
                            </span>
                            <span>
                                <el-button type="primary" round size="small" v-show="data.level !== 2"
                                    @click="append(node, data)">添加</el-button>
                                <el-button type="warning" round size="small" v-show="data.id !== 0"
                                    @click="edit(node, data)">编辑</el-button>
                                <el-button type="danger" round size="small"
                                    v-show="!data.childrenList || data.childrenList.length <= 0"
                                    @click="remove(node, data)">删除</el-button>
                            </span>
                        </span>
                    </template>
                </el-tree>
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="Tips" width="30%" @opened="openfrom" destroy-on-close>
            <el-form ref="ruleFormRef" :model="dataForm" status-icon :rules="rules" class="demo-ruleForm"
                label-width="100px">
                <el-form-item prop="title" label="类目名称">
                    <el-input class="fix_input" v-model.trim="dataForm.title" type="text" autocomplete="off"
                        placeholder="请输入广告标题" />
                </el-form-item>

                <el-form-item label="类目图片" prop="picUrl" id="upload" ref="uploadRef" class="is-required">
                    <el-upload class="avatar-uploader" action="http://192.168.1.188:8080/upload/admin" :headers="headers"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

            </el-form>


            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="sure(ruleFormRef);">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { post } from '@/utils/http';
import { ElMessage, ElMessageBox, ElNotification, type FormInstance, type UploadProps } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import type { ClassCategoryTree } from '#/index';
import type Node from 'element-plus/es/components/tree/src/model/node'
import cookie from 'js-cookie'
import { theColorFn } from '@/utils/theColorFn';

const dialogVisible = ref(false)
const Tips = ref("")
let treedata: ClassCategoryTree[] = reactive([])
let listLoading = ref(false)            //加载效果
const uploadRef = ref()
const ruleFormRef = ref<FormInstance>()

// 添加传递的数据
let dataForm: TypeCategory = reactive({
    title: '',              //类目名称
    parentId: 0,            //父id
    iconUrl: '',            //图标
    picUrl: '',             //图片
})
/**
 * 添加时清空参数
 */
let newForms = { ...dataForm }

// 数据初始化
onMounted(() => {
    init()
})

/**
 * 表单验证
 */
const rules = {
    title: [
        { required: true, message: "类目名称不得为空！", trigger: 'blur' },
    ],
}

/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let categoryListData = reactive({
        _gp: "category",
        _mt: "categoryList",

    })
    // 请求管理员列表接口拿到管理员列表信息
    post(categoryListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data, errno, errmsg } = res
        if (200 === errno) {
            treedata.length = 0;
            console.log(data);
            let obj:Array<object> = [{
                title:"全部类目"
            }]

            treedata.push(...data)
            // treedata = [{title:'全部类目',id:0,childrenList:[...data]}]
            listLoading.value = false

        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);
    })
}

/**
 * 添加
 */
const append = (node: Node, data: ClassCategoryTree) => {
    console.log(node, data);
    Tips.value = "添加"
    Object.assign(dataForm, newForms)
    dataForm.parentId = data.id
    dialogVisible.value = true

}
/**
 * 修改
 */
const edit = (node: Node, data: ClassCategoryTree) => {
    console.log(node, data);
    Tips.value = "修改"
    Object.assign(dataForm, data)
    dialogVisible.value = true

}
/**
 * 删除
 */
const remove = (node: Node, data: ClassCategoryTree) => {
    console.log(node, data);
    let deletData = {
        _gp: 'admin.category',
        _mt: 'delete',
        id: data.id
    }

    ElMessageBox.confirm('真的要删除吗？')
        .then(() => {
            post(deletData).then(res => {
                // console.log(res);
                let { errno,errmsg } = res
                if (200 === errno) {
                    ElMessage.success('删除成功')
                    init()
                }else{
                    ElMessage.error(errmsg)
                }
                
            }).catch(err => {
                console.log(err);
                
            })
        })
        .catch(() => {
            ElMessage.error("取消删除！")
        })
}

/**
 * 添加和修改功能
 * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {

    console.log(dataForm);
    
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log("=====要提交的表单数据=====");
            console.log(dataForm);
            let data = {
                _gp: 'admin.category',
                _mt: Tips.value == "添加" ? 'create' : 'update',
                ...dataForm
            }
            post(data).then(res => {
                console.log(res);

                let { errno } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    ElMessage.success(Tips.value == "添加" ? '添加成功' : '修改成功')
                    init()
                }
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}

/**
 * 上传图片添加请求头
 */
const headers = reactive({
    AdminToken: cookie.get('token')
})

/**
 * 验证图片格式
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式只能是 JPG格式 !')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

/**
 * 上传图片
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dataForm.picUrl = response.url
    dataForm.picUrl = response.url // 得到上传图片成功的路径
    // theColorFn(dataForm.picUrl, (callback: string) => {
    //     dataForm.color = callback
    // }) // 计算得到图片平均色
    // console.log(dataForm.color);

    init()
}

function openfrom() {
    // uploadRef.value.$el.style.backgroundColor = dataForm.color;
}
</script>

<style scoped lang="less">
.box-card {
    width: 100%;

    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.tree_icon {
    width: 15px;
    position: relative;
    top: 4px;
}
</style>